﻿using bilibili下载.Help;
using bilibili下载.Interface;
using bilibili下载.Models;
using Microsoft.WindowsAPICodePack.Dialogs;
using NLog;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace bilibili下载.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        public MainWindowViewModel()
        {
            AnalysisCommand = new DelegateCommand<string>(Analysis);
            PathCommand = new DelegateCommand(SetPath);
            CheckedAllCommand = new DelegateCommand(CheckedAll);
            InvertCommand = new DelegateCommand(InvertSelection);
            DownloadCommand = new DelegateCommand<string>(Download);
            Quantity = 3;
        }

        private string _title = "哔哩哔哩视频下载";

        /// <summary>
        /// 标题
        /// </summary>
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        private string _url;

        /// <summary>
        /// 视频地址
        /// </summary>
        public string Url
        {
            get { return _url; }
            set { SetProperty(ref _url, value); }
        }

        private int quantity;

        /// <summary>
        /// 并发数量
        /// </summary>
        public int Quantity
        {
            get { return quantity; }
            set { SetProperty(ref quantity, value); }
        }

        /// <summary>
        /// 解析视频
        /// </summary>
        public DelegateCommand<string> AnalysisCommand { get; private set; }

        /// <summary>
        /// 设置保存路径
        /// </summary>
        public DelegateCommand PathCommand { get; private set; }

        /// <summary>
        /// 全部选中
        /// </summary>
        public DelegateCommand CheckedAllCommand { get; private set; }

        /// <summary>
        /// 反选
        /// </summary>
        public DelegateCommand InvertCommand { get; private set; }

        /// <summary>
        /// 下载
        /// </summary>
        public DelegateCommand<string> DownloadCommand { get; private set; }

        private string path;

        /// <summary>
        /// 保存路径
        /// </summary>
        public string Path
        {
            get { return path; }
            set { SetProperty(ref path, value); }
        }

        private IAnalysis aVInfos;

        /// <summary>
        /// 视频列表信息
        /// </summary>
        public IAnalysis AVInfos
        {
            get { return aVInfos; }
            set { SetProperty(ref aVInfos, value); }
        }

        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 解析视频
        /// </summary>
        /// <param name="url"></param>
        private void Analysis(string url)
        {
            try
            {
                if (AnalysisFactory.Factory(url, out var aVs))
                {
                    AVInfos = aVs;
                }
                else MessageBox.Show("连接解析失败,请检查连接");
            }
            catch (Exception e)
            {
                logger.Error(e, "视频地址解析失败");
            }
        }

        /// <summary>
        /// 设置保存路径
        /// </summary>
        private void SetPath()
        {
            var dialog = new CommonOpenFileDialog
            {
                IsFolderPicker = true
            };
            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                Path = dialog.FileName;
            }
        }

        private void CheckedAll()
        {
            if (AVInfos != null)
            {
                foreach (var item in AVInfos)
                    item.Checked = true;
            }
        }

        private void InvertSelection()
        {
            if (AVInfos != null)
            {
                foreach (var item in AVInfos)
                    item.Checked = !item.Checked;
            }
        }

        private bool isEnabled = true;

        /// <summary>
        /// 按钮是否可用
        /// </summary>
        public bool IsEnabled
        {
            get { return isEnabled; }
            set { SetProperty(ref isEnabled, value); }
        }

        private async void Download(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                if (AVInfos != null)
                {
                    IsEnabled = false;
                    await DownloadAsync(path);
                    IsEnabled = true;
                }
            }
            else MessageBox.Show("请输入保存路径");
        }

        private async Task DownloadAsync(string path)
        {
            await Task.Run(() =>
               {
                   using (var myTask = new MyTask(Quantity, true))
                   {
                       foreach (var item in AVInfos.Where(a => a.Checked))
                       {
                           item.State = State.Await;
                           myTask.Run(() =>
                           {
                               item.Download(path);
                           });
                       }
                   }
                   ;
               });
        }
    }
}